package com.application.service;

import com.application.common.utils.ImageUtils;
import com.application.model.Global;
import com.application.module.couponget.CouponGet;
import com.jfinal.ext.kit.MsgException;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.platform.annotation.Service;
import com.platform.mvc.base.BaseService;
import com.platform.mvc.user.User;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.IOException;
import java.sql.Timestamp;

@Service(name = UserService.serviceName)
public class UserService extends BaseService {

	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(UserService.class);
	
	public static final String serviceName = "userService";

	public User registerUser(String mobile) {
		return registerUser(mobile, null, null, mobile, null);
	}

    /**
     * 创建用户
     * @param mobile
     * @param openid
     * @param openType
     * @param name
     * @param imgUrl
     * @return
     */
	public User registerUser(String mobile, String openid, String openType, String name, String imgUrl) {
	    String username = StrKit.isBlank(mobile) ? openid : mobile;
        //下载头像
		String path = "/files/download/user/" + username + ".png";

		User user = new User().set(User.column_username, username).set("mobile", mobile).set("name", name);

		if(imgUrl != null){
			try {
				String img = ImageUtils.downloadFile(imgUrl, path);
				user.set("img", img);
			} catch (IOException e) {
				e.printStackTrace();
				throw new MsgException("用户头像下载失败");
			}
		}

		if(openid != null){
			user.set("openid", openid);
		}
		if(openType != null){
			user.set("open_type", openType);
		}

		Global global = Global.cacheGetByCode(Global.Code.defaultPassword);
		user.setPassword(DigestUtils.md5Hex(global.getValue()));
		user.set("create_at", new Timestamp(System.currentTimeMillis()));
		user.save();

		user = User.dao.findByUsername(username);
		user.remove(User.column_password).remove("pay_pass");

		//赠送注册优惠券
		//UserCoupon.dao.create(user.getId(), 1);
        CouponGet.dao.addNewUser(user.getId());

        //创建用户详细信息
//        Userinfo.dao.create(user.getId());

		return user;
	}

	public User getUserinfo(String username) {
		User user = User.dao.findByUsername(username);
		user.remove(User.column_password).remove("pay_pass");
		return user;
	}
}
